|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
using namespace std;
class Books{
public:
Books(float pri,char* na,char *au,char *pu):price(pri),name(na),author(au),pub(pu){}
char* getName(){return name;}
void printinfo(){
cout<<price;
}
private:
const float price;
char *name;
char *author;
char *pub;
};
int main(){
Books b[4]={
(39,"平凡的世界","路遥","上海交通大学出版社"),
(32.6,"假如给我三天光明","海伦凯勒","上海交通大学出版社"),
(21.4,"活着","余华","电子科技大学出版社"),
(45,"老人与海","海明威","北京师范大学出版社")}; //这里报错
char *search;
cout<<"请输入要查询的书名:";
cin>>search;
for(int i = 0;i<5;i++){
if(*b[i].getName() == *search){
b[i].printinfo();
}
}
}
报错信息:[Error] conversion from 'const char [19]' to non-scalar type 'Books' requested
#include <iostream>
using namespace std;
class Books{
public:
Books(float pri,char* na,char *au,char *pu):price(pri),name(na),author(au),pub(pu){}
char* getName(){return name;}
void printinfo(){
cout<<price;
}
private:
const float price;
char *name;
char *author;
char *pub;
};
int main(){
//语法错误,应该改成
Books b[4]= {
Books(39,"平凡的世界","路遥","上海交通大学出版社"),
Books(32.6,"假如给我三天光明","海伦凯勒","上海交通大学出版社"),
Books(21.4,"活着","余华","电子科技大学出版社"),
Books(45,"老人与海","海明威","北京师范大学出版社")};
//这么定义的字符串指针没有分配内存地址,是无法使用的。
//应该用以下几种方式定义:
//1: char search[64] = {0};
//2: char * search = new char [64];
//3: 用stl 的 string 类 std::string search;
//相同的道理,在类里面定义的字符串指针也是有问题的。
//但是,上面的数组 b 的初始化没有问题。
char *search;
cout<<"请输入要查询的书名:";
cin>>search;
for(int i = 0;i<5;i++)
{
// c/c++不支持字符串 == 操作
//应该用函数 if(strcmp(str1,str2) == 0)
//加* 只是比较第一个字符是否相等
if(*b[i].getName() == *search)
{
b[i].printinfo();
}
}
return 0;
}
|
|