运算符重载

发布于 2024-09-17 19:36:41 字数 1674 浏览 8 评论 0原文

我创建了一个类 myString 并且尝试运行以下代码:

class myString{
    char* str;
    int len;

public:
    myString(char* str1 = " "){
        len = strlen(str1);
        str = new char[len+1];
        strcpy(str, str1);
    };

    int getLen() const {
        return len;
    };

    char* getString() const {
        return str;
    };

    ~myString(){
        delete[] str;
    };

    myString& operator=(myString& orig){
        cout << "hello";
        if (str == NULL){
            delete[] str;
        };
        str = new char[orig.getLen()];
        strcpy(str, orig.getString());
        cout << this << endl;
        return *this;
    };

    ...
};



int main(){


    myString s("bla");
    myString k("dingo");
        myString g = s;
        // s=k;  //When this line is commented I get a linking error
         ...
   };

我的问题:

  1. 为什么不打印“hello”?
  2. 为什么 s=k 行会导致链接器错误?

这是错误:

链接:c:\users\perry\documents\visual studio 2010\Projects\inheritance\Debug\inheritance.exe 未找到或未构建 通过最后一个增量链接;执行完整链接 1>main.obj :错误 LNK2019:未解析的外部符号“类” std::basic_ostream > & __cdecl 运算符<<(类 std::basic_ostream

<块引用>

&,class myString *)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@PAVmyString@@@Z) 在函数“public: class myString & __thiscall”中引用 myString::operator=(class myString &)" (??4myString@@QAEAAV0@AAV0@@Z) 1>c:\users\perry\documents\Visual Studio 2010\Projects\inheritance\Debug\inheritance.exe:致命错误 LNK1120: 1 个未解决的外部问题

谢谢, 李

I've created a class myString and I'm trying to run the following code:

class myString{
    char* str;
    int len;

public:
    myString(char* str1 = " "){
        len = strlen(str1);
        str = new char[len+1];
        strcpy(str, str1);
    };

    int getLen() const {
        return len;
    };

    char* getString() const {
        return str;
    };

    ~myString(){
        delete[] str;
    };

    myString& operator=(myString& orig){
        cout << "hello";
        if (str == NULL){
            delete[] str;
        };
        str = new char[orig.getLen()];
        strcpy(str, orig.getString());
        cout << this << endl;
        return *this;
    };

    ...
};



int main(){


    myString s("bla");
    myString k("dingo");
        myString g = s;
        // s=k;  //When this line is commented I get a linking error
         ...
   };

My Questions:

  1. Why "hello" does not get printed?
  2. Why the line s=k causes a linker error?

This is the error:

LINK : c:\users\perry\documents\visual studio
2010\Projects\inheritance\Debug\inheritance.exe not found or not built
by the last incremental link; performing full link 1>main.obj : error
LNK2019: unresolved external symbol "class
std::basic_ostream > & __cdecl
operator<<(class std::basic_ostream

&,class myString *)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@PAVmyString@@@Z)
referenced in function "public: class myString & __thiscall
myString::operator=(class myString &)" (??4myString@@QAEAAV0@AAV0@@Z)
1>c:\users\perry\documents\visual studio
2010\Projects\inheritance\Debug\inheritance.exe : fatal error LNK1120:
1 unresolved externals

Thanks,
Li

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

猫腻 2024-09-24 19:36:41

对于以下内容,您需要一个复制构造函数。它不使用赋值运算符函数。

myString g = s;

编辑

对于链接器错误 - 我无法帮助您。我不会猜测该行调用的operator<<,而是放弃此操作,因为您还没有提供代码。在普通的 C++ 代码中,简单的 cout << 是不可能的。 this; 会导致链接器错误。 cout 有一个接受 void const* 的运算符。您已在某处声明了一个提供更好匹配的运算符,但没有定义它。

For the following, you need a copy constructor. It does not use the assignment operator function.

myString g = s;

Edit

For the linker error - I can't help you with that. Rather than guessing at what operator<< that line calls, I will just give up on this because you haven't provided the code. In normal C++ code, there is no way that a simple cout << this; would cause a linker error. cout has an operator that accepts a void const* for this. You have declared an operator somewhere that provides a better match but did not define it.

合约呢 2024-09-24 19:36:41

链接错误是你没有定义

operator<<(class std::basic_ostream< >  &,class myString *)

由于该行

cout << this << endl;

Link error is that you have not defined

operator<<(class std::basic_ostream< >  &,class myString *)

due to the line

cout << this << endl;
这样的小城市 2024-09-24 19:36:41

我认为应该是

operator=(const myString &orig)

I think it should be

operator=(const myString &orig)
绮筵 2024-09-24 19:36:41
myString g = s;

这不会调用operator=,而是调用复制构造函数。由于您尚未定义任何复制构造函数,因此会生成一个默认复制构造函数,复制所有字段。但你持有指针,你不希望这种情况发生!这就是为什么你需要一个复制构造函数。

关于链接错误:

cout << this << endl;

在这里,您尝试对此使用 operator<< 。该类型为myString*,未定义该运算符。如果你想打印 this 指针的值,你可以转换它:

cout << (void*) this << endl;

 if (str == NULL){
                delete[] str;
            };

你想要if (str != NULL)在这里(打字错误?)。

myString g = s;

This doesn't call operator=, but the copy constructor. Since you have not defined any copy constructor, a default one is generated, copying all fields. But you're holding pointers, you don't want that to happen ! That's why you need a copy constructor.

About the linking error:

cout << this << endl;

Here, you try to use operator<< with this. The type of this is myString*, for which this operator is not defined. If you want to print the value of the this pointer, you can convert it:

cout << (void*) this << endl;

 if (str == NULL){
                delete[] str;
            };

You want if (str != NULL) here (typo ?).

绝影如岚 2024-09-24 19:36:41

首先,myString g = s;是一个新的myString的初始化,这是通过复制构造函数完成的(它是自动提供的,因为你没有编写一)。

链接错误是由于行 cout <<;这个<< endl;,因为你还没有告诉系统如何打印this,而且它显然想不出办法。

在 C++ 中,有“三法则”:如果您编写复制构造函数、赋值运算符或析构函数,您可能需要编写所有这三个函数。 (例外情况是为基类编写虚拟析构函数。)通常,您的类管理一些资源(在您的情况下为 str),并且您需要在所有三种情况下处理它。

另外,如果可以的话,请使用const。您可以将非 const 变量传递给 const 引用,但反之则不然。

你的析构函数没问题。您的赋值运算符应具有签名 myString & operator=(const &myString),并且您的复制构造函数应具有签名 myString::myString(const &myString)

In the first place, myString g = s; is the initialization of a new myString, and that's done with the copy constructor (which is automatically provided because you didn't write one).

The link error is because of the line cout << this << endl;, since you haven't told the system how to print this, and it apparently can't come up with a way.

In C++, there's the Rule of Three: if you write a copy constructor, assignment operator, or destructor, you probably need to write all three. (The exception is writing a virtual destructor for a base class.) Typically, then, your class manages some resource (str in your case), and you need to handle it in all three cases.

Also, use const when you can. You can pass a non-const variable into a const reference, but not vice versa.

Your destructor is fine. Your assignment operator should have the signature myString & operator=(const &myString), and your copy constructor should have the signature myString::myString(const &myString).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文