运算符不使用 Class 个对象?

Operators Not Working With Class Objects?

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

您在 void 函数上调用 instream 运算符

std::cin >> testObject.setName;

你需要先以字符串形式输入,然后调用setter设置值

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

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

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

或使用Operator Overloading重载>>.