我想重载赋值运算符,以便在初始化对象时用它来分配数据
用于初始化字符串对象,我们可以遵循下面给出的格式
string str = "Hello World !!!";
但如果我们以相同的方式定义对象,那将是一个错误;
例如
#include<iostream>
using namespace std;
class Name{
private:
string name;
public:
Name(){}
Name(string str){
name=str;
}
};
int main(){
Name name="Jack";
}
显示错误,如
E:\Documents\test.cpp||In function 'int main()':|
E:\Documents\test.cpp|13|error: conversion from 'const char [5]' to non-scalar type 'Name' requested|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
所以如何使一个类能够接受像string对象这样的数据。
答案 0 :(得分:1)
首先,Name name="Jack";
是初始化,而不是赋值,因此它与赋值运算符无关。
请注意,"Jack"
不是std::string
,而是类型为const char[5]
的字符串文字。然后,对于Name name="Jack";
copy initialization,需要将其转换为std::string
,然后转换为Name
。但在一个转换序列中只允许一个用户定义的转换。
您可以使用const char*
,
class Name{
...
Name(const char* s) : name(s) {}
};
从const char[]
到const char*
的Implicit conversion被视为标准转换,然后代码正常运行。
或者将Name name="Jack";
更改为Name name("Jack");
,direct initialization,"Jack"
将转换为std::string
,Name
的构造函数将更改为std::string
将直接调用Name name = "Jack"s;
来初始化对象。
或者使用"Jack"s
,而std::string
是std::string
literal(自C ++ 14以来)类型std::string
,则只有一次转化(来自Name
需要// Notify the rooms
if(previousRoomID) io.to(previousRoomID).emit("activity-notification","<b>"+socket.me.name+"</b> has left the room " + previousRoomID);
io.to(socket.room.id).emit("activity-notification","<b>"+socket.me.name+"</b> has joined the room " + socket.room.id);
)。
答案 1 :(得分:1)
此行的右侧(不是赋值,而是对象定义和初始化):
Name name = "Jack";
调用fifth string constructor overload因为&#34; Jack&#34;是const char[]
类型的string literal而不是std::string
,这是您的用户定义Name(string str)
构造函数所期望的。要使其类型为std::string
,请使用operator ""s附加s
字面值,以构建std::string
类型的文字:
Name name = "Jack"s;
并在启用C ++ 14支持的情况下进行编译,或者添加一个接受const char*
参数的构造函数:
Name(const char* str) {
name = str;
}
使用<string>
类型时,您需要包含std::string
标头。