作者easterday (....)
看板C_and_CPP
標題[問題] 有關C++Primer中文版,p461頁(12.4.4)
時間Fri Aug 2 13:57:32 2013
上次經過大家的幫忙,終於讓我比較了解這一節在做甚麼
但是又有新的疑問了...
#include <string>
#include <iostream>
using namespace std;
class Sales_item
{
public:
friend istream& operator>>(istream& in, Sales_item& s);
std::string isbn;
int unit_sold;
double revenue;
Sales_item(const std::string &book="")
:isbn(book),unit_sold(0),revenue(0.0) {}
Sales_item(istream& is);
bool same_isbn(const Sales_item& that) const;
};
Sales_item::Sales_item(istream& is)
{
is>> *this;
}
bool Sales_item::same_isbn(const Sales_item& that) const
{
return (isbn==that.isbn);
}
istream& operator>>(istream& in, Sales_item& s)
{
double price;
in>> s.isbn >> s.unit_sold >> price;
if (in)
s.revenue= s.unit_sold * price;
else
s=Sales_item();
return in;
}
class ESales_item
{
public:
friend istream& operator>>(istream& in, ESales_item& s);
std::string isbn;
int unit_sold;
double revenue;
explicit ESales_item(const std::string &book="")
:isbn(book),unit_sold(0),revenue(0.0) {}
explicit ESales_item(istream& is);
bool same_isbn(const ESales_item& that) const;
};
ESales_item::ESales_item(istream& is)
{
is>> *this;
}
bool ESales_item::same_isbn(const ESales_item& that) const
{
return (isbn==that.isbn);
}
istream& operator>>(istream& in, ESales_item& s)
{
double price;
in>> s.isbn >> s.unit_sold >> price;
if (in)
s.revenue= s.unit_sold * price;
else
s=ESales_item();
return in;
}
int main()
{
Sales_item item(string("9"));
string null_book = "9";
// cout << item.same_isbn("999")<<endl; //compiling err
cout << item.same_isbn(null_book)<<endl;
// cout<< item.same_isbn(cin)<<endl; //good
ESales_item item2(string("9"));
//item2.same_isbn(null_book); //compling err
//item2.same_isbn(cin); //compilng err
ESales_item another("9");
//explicit的功用應該是禁止隱式轉換,為什麼又把const char* ==>string了??
cout << item2.same_isbn(another) <<endl;
getchar();
return 0;
}
explicit的功用應該是禁止隱式轉換
但是為什麼又把const char*轉換成了string??
--
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.38.228.150
推 Feis:Explicit 的不是string(const char*) 08/02 15:00
→ easterday:我觀察到的現象是,沒有explicit時 08/02 16:15
→ easterday:const char*不能轉換成string 08/02 16:15
推 purpose:ESales_item another("9"); 這裡的隱式轉換是將 "9" 轉成 08/02 16:30
→ purpose:std::string 物件,所以是歸 class string 管,所以可以過 08/02 16:30
→ easterday:那為什麼Sales_item item2("9");這樣不能過? 08/02 22:43
→ easterday:我想我知道問題了,item2名子衝到了... 08/02 22:57