| 网站首页 | 业界新闻 | 小组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛

```#include<iostream>
#include<string>
class Stock{
private:
std::string co;
double gat;
int total;
public:
Stock(const std::string s,int i=0,double j=0.0);
const Stock &val(const Stock &s)const;
void show()const;
};
void Stock::show()const{
std::cout<<co<<std::endl<<total<<std::endl<<gat;
}
Stock::Stock(const std::string s,int i,double j){
co=s;
total=i;
gat=j;
}
const Stock &Stock::val(const Stock &s)const{
if(s.total>total)
return s;
else
return *this;
}

int main(){
Stock stock1[4]={
Stock("skg",4,7.7),
Stock("skgjg",5,3.9),
Stock("irgnj",33,5.7),
Stock("eiur",4,5.7)
};
const Stock *p=&stock1[0];
for(int i=1;i<4;i++){
p=&p->val(stock1[1]);
}
p->show();
return 0;
}```

skgjg
5
3.9

`const Stock &val(const Stock &s)const;`

const Stock &val(const Stock s)const;

`const Stock &Stock::val(const Stock &s)const{`

const Stock &Stock::val(const Stock s)const{

```const Stock &Stock::val(const Stock s)const{
if(s.total>total)
return s;
else
return *this;
}```

```#include <iostream>
#include <string>
#include <algorithm>

class Stock
{
public:
explicit Stock( const std::string co, int total=0, double gat=0.0 );
bool operator<( const Stock& rhs ) const;
friend std::ostream& operator<<( std::ostream& os, const Stock& obj );
private:
std::string co_;
double gat_;
int total_;
};

Stock::Stock( const std::string co, int total, double gat ) : co_(co), total_(total), gat_(gat)
{
}
bool Stock::operator<( const Stock& rhs ) const
{
}
std::ostream& operator<<( std::ostream& os, const Stock& obj )
{
return os << obj.co_ << '\n' << obj.total_ << '\n' << obj.gat_;
}

int main( void )
{
Stock s[4] = {
Stock("skg",    4, 7.7),
Stock("skgjg",  5, 3.9),
Stock("irgnj", 33, 5.7),
Stock("eiur",   4, 5.7)
};

auto itor = std::max_element( std::begin(s), std::end(s) );
std::cout << *itor << std::endl;
}```

```#include<iostream>
#include<string>
class Stock{
private:
std::string co;
double gat;
int total;
public:
Stock(const std::string s,int i=44,double j=55);
const Stock val(const Stock &s)const;
void show()const;
};
void Stock::show()const{
std::cout<<co<<std::endl<<total<<std::endl<<gat;
}
Stock::Stock(const std::string s,int i,double j){
co=s;
total=i;
gat=j;
}
const Stock Stock::val(const Stock &s)const{
if(s.total>total)
return s;
else
return *this;
}

int main(){
Stock stock1[4]={
Stock("skg",46,77.7),
Stock("skgjg",5,3.9),
Stock("irgnj",33,5.7),
Stock("eiur",4,5.7)
};
const Stock *p=&stock1[0];
for(int i=1;i<4;i++){
p=&p->val(stock1[1]);
}
p->show();
return 0;
}```

[此贴子已经被作者于2021-4-18 04:13编辑过]

*this 不是临时对象，就是这个类对象自身

*this 不是临时对象，就是这个类对象自身

*this 不是临时对象，但你的
const Stock Stock::val(const Stock &s)const

p=&p->val(stock1[1]);

“未定义行为”没有为什么
• 6
• 1/1页
• 1