Visual Studio 2010 上的C++:无法将字符串分配给字符串(不支持混合类型)

C++ on Visual Studio 2010: Cannot assign string to a string (mixed types are not supported)

本文关键字:字符串 分配 混合 类型 不支持 上的 2010 Studio C++ Visual      更新时间:2023-10-16

我正在尝试做一些非常简单的事情...在类中声明一个字符串,然后将其分配给类构造函数中定义的另一个字符串的值。

我正在为非托管类"非托管"使用托管包装器(使用托管包装器,因为我想在 C# 程序中使用它,而我使用的东西是非托管的,它的.sln文件不受我的控制)

如您所见,我尝试包含尽可能多的字符串标头。

#pragma once
#include <string>
#include <string.h>
#include <cstring>
#include <iostream>
using namespace std;
using namespace System;
using std::string;
namespace UnmanagedWrap {
    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    public:
        Unmanaged *pu; //pointer to the Unmanaged class
        //the constructor will allocate the pointer pu
        int a;
        int b;
        std::string filePath; //try CString() when get back
        Class1(int a_In, int b_In, std::string filePath_In) : pu(new Unmanaged()) { //constructor
            a = a_In;
            b = b_In;
            filePath = filePath_In; //trying to assign filePath to the inputted filePath_In.......
            }; //end of constructor

这给了我 2 个错误:

第一个与线路std::string filePath;有关

1>c:usersngracedocumentsvisual studio 2010projectsunmanagedwrapunmanagedwrapUnmanagedWrap.h(21): error C4368: cannot define 'filePath' as a member of managed 'UnmanagedWrap::Class1': mixed types are not supported

第二个与线路filePath = filePath_In;有关

1>c:usersngracedocumentsvisual studio 2010projectsunmanagedwrapunmanagedwrapUnmanagedWrap.h(25): error C2678: binary '=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)

我很迷茫,因为我花了几个小时寻找答案......

我去寻求帮助的一些页面:

在 C++/CLI 代码中包含来自非托管C++代码的标头

不支持混合类型

(我会发布更多,但我需要至少 10 的声誉才能这样做......

关于为什么我会收到这些错误的任何想法?

使用Bo Persson和user2666293的信息,我被引导尝试了一些东西,最终得到了答案。

必须对托管字符串使用 System::String^ 类型。如果使用托管字符串并将其传递给非托管类中的方法,则必须将其转换为非托管字符串类型!

假设我们在非托管类中使用非托管字符串类型 std::string

从 System::String^std:string 的转换必须使用以下方法完成:

 auto unmannedString = msclr::interop::marshal_as<std::string>(managedString);

并在以下位置顶部显示头文件引用:

#include <msclr/marshal_cppstd.h>

其中托管字符串的类型为 System::String^

:)

https://msdn.microsoft.com/en-us/library/hh699870.aspx 在

项目符号 2 下说,ref 类只有在它们不是公共的时才可以具有标准 C++ 类型。尝试使用常规类或将 filePath 设为私有。

编辑:我不熟悉托管类,但您可以尝试 Platform::string 而不是 std::string : https://msdn.microsoft.com/en-us/library/hh755812.aspx

https://msdn.microsoft.com/en-us/library/hh699879.aspx表示在将字符串来回传递到 Windows 运行时类中的方法时,或者与其他 Windows 运行时组件交互时使用平台字符串