【问题标题】:Operators Not Working With Class Objects?运算符不使用类对象?
【发布时间】:2017-10-20 04:43:51
【问题描述】:

我正在尝试学习 C++,并且正在创建一些小程序来测试它是如何工作的。我编写了这段代码,但由于某种原因,我在编译时遇到了这个错误:

binary '>>': no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)

如果有人能帮我解决这个问题,我将不胜感激。

代码:

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <string>
#include "logo.h"

class classTest
{
    public:
        void setName(std::string x)
        {
            name = x;
        }

        std::string getName()
        {
            return name;
        }
    private:
        std::string name;
};

int main()
{
    SetConsoleTitle("plains.exe");

    displayLogo();

    std::cout << "Please enter your name: ";

    classTest testObject;
    std::cin >> testObject.setName;

    std::cout << "Your name is " << testObject.getName() << "." << std::endl;

    return 0;
}

【问题讨论】:

    标签: c++ class object operators


    【解决方案1】:

    setName 是一个函数。所以,你不能使用cin &gt;&gt; testObject.setName。你可以这样做-

    string name;
    cin >> name;
    testObject.setName(name);
    

    或使用Operator Overloading 重载&gt;&gt;

    【讨论】:

    • Asker 也可以将std::string getName() 更改为std::string &amp; getName() 然后cin &gt;&gt; testObject.getName()
    • 确实如此。但通常类变量是通过 set 方法设置的。
    【解决方案2】:

    您正在对 void 函数调用 instream 运算符

    std::cin >> testObject.setName;
    

    你需要先把输入取成一个字符串,然后调用setter来设置值

    string inputName;
    std::cin>>inputName;
    testObject.setName(inputName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多