c++ - C++ 中使用指针传递 Char

标签 c++ oop pointers

我对函数传递的指针和字符的图像不清楚。请任何人都可以告诉我我在哪里做错了,并简要介绍一下指针?例如:我应该在哪里使用它们,等等...

#include <iostream>
using namespace std;
class book{
private:
    char *CName;
    int CFee;
    int NoPeople;
    int Income;
public:
    void setData(char &x,int y,int z){
        CName = &x;
        CFee = y;
        NoPeople = z;

    }
    void calIncome(){
        Income = CFee * NoPeople;

    }
    void viewIncome(){
        cout<<Income;
        cout<<CName;

    }
};
int main(){
    book b1;
    b1.setData('DISE',20000,30);
    b1.calIncome();
    b1.viewIncome();
}

我在这段代码中遇到错误

//b1.setData('DISE',20000,30); “对‘char’类型的非常量左值引用不能绑定(bind)到‘int’类型的临时值”

最佳答案

在您的代码中不需要指针。您应该使用 std::string:

#include <string>
...
string CName
...
void setData(const string& x,int y,int z){
  CName = x;

并且在 setData 调用中,您应该使用双引号(用于字符串)而不是单引号(用于单个字符)。

关于c++ - C++ 中使用指针传递 Char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22608079/

相关文章:

C++ 输入运算符重载 ">>"

c++ - 模板化类型定义和继承

c - 指向函数中结构数组的指针

c++ - 使用 boost::range::sort

c++ - 如何在头文件中组织代码实体?

c++ - 委派构造函数和模板

c# - 有人想过以这种方式使用黑板模式吗?

c++ - 类字段重置为零

c++ - 遍历指针列表时出现问题 - C++

c - 编译困难 : Pointers in C