gpt4 book ai didi

c++ - 使用指针在 C++ 中传递的字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:19 24 4
gpt4 key购买 nike

我对通过函数传递的指针和字符的印象不清晰。请任何人都可以告诉我我在哪里做错了关于指针的简要想法?例如:我应该在哪里使用它们等等......

#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++ 中传递的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22608079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com