运算符不使用类对象?

时间:2017-10-20 04:43:51

标签: c++ class object operators

我正在尝试学习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;
}

2 个答案:

答案 0 :(得分:1)

setName是一个功能。因此,您无法使用cin >> testObject.setName。你可以这样做 -

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

或使用Operator Overloading重载>>

答案 1 :(得分:0)

您正在调用void函数

上的instream运算符
std::cin >> testObject.setName;

您需要首先在字符串中输入输入,然后调用setter来设置值

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