Visual Studio 2010 上的C++:无法将字符串分配给字符串(不支持混合类型)
C++ on Visual Studio 2010: Cannot assign string to a string (mixed types are not supported)
我正在尝试做一些非常简单的事情...在类中声明一个字符串,然后将其分配给类构造函数中定义的另一个字符串的值。
我正在为非托管类"非托管"使用托管包装器(使用托管包装器,因为我想在 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^
:)
项目符号 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 运行时组件交互时使用平台字符串
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 无法在 c++ 中将字符串分配给字符串数据类型
- 将字符串* 分配给字符* c++
- 如何为C++字符串分配空指针参数?
- 为什么在构造函数中将字符串分配给指针是安全的?
- 如何将wchar_t字符串分配给用户定义类的 CString 成员
- 字符串分配
- 如何将字符串分配给向量(均在堆上)
- 确实为其写入的字符串分配内存
- 简单的字符串分配导致分割故障
- 通过新行不使用字符串流将C 字符串分配
- 将字符串分配到动态数组位置时出错
- 在 c++ 中为字符串分配其分配的大小值是否正确
- 从被空间分开的字符串分配给变量?C [QT]
- 将字符串分配给固定长度的字符数组
- 将一组字符串分配给向量c++的内容
- 如何为字符串分配内存
- C++中的字符串分配:为什么这样做
- 视觉 建议在C++中执行字符串分配什么?
- 字符 *str;str= "HELLO" ;如何在不为字符串分配任何内存的情况下工作?