注册 登录
编程论坛 C++教室

这个错误如何修改?

hffjhhh 发布于 2021-01-08 18:01, 1472 次点击
这行显示以下错误:
p->show();

[Error] passing 'const Stock' as 'this' argument of 'void Stock::show()' discards qualifiers [-fpermissive]

代码如下:
程序代码:
#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();
};
void Stock::show(){
    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;
}
2 回复
#2
rjsp2021-01-08 19:02
void show() const
void Stock::show() const
#3
rjsp2021-01-08 19:25
当然,整段代码都不是C++风格,这是半路转行C++的C程序员的通病

程序代码:
#include <iostream>
#include <string>

class Stock
{
public:
    explicit Stock( std::string co, int total=0, double gat=0.0 );

private:
    std::string co_;
    int total_;
    double gat_;
   
    friend bool operator<( const Stock& lhs, const Stock& rhs ) noexcept;
    friend std::ostream& operator<<( std::ostream& os, const Stock& s );
};

Stock::Stock( std::string co, int total, double gat ) : co_(std::move(co)), total_(total), gat_(gat)
{
}

bool operator<( const Stock& lhs, const Stock& rhs ) noexcept
{
    return lhs.total_ < rhs.total_;
}

std::ostream& operator<<( std::ostream& os, const Stock& s )
{
    return os << s.co_ << '\n' << s.total_ << '\n' << s.gat_;
}

#include <algorithm>
using namespace std;

int main( void )
{
    Stock s[] = {
        Stock("skg",    4, 7.7),
        Stock("skgjg",  5, 3.9),
        Stock("irgnj", 33, 5.7),
        Stock("eiur",   4, 5.7)
    };
   
    auto itor = max_element( begin(s), end(s) );
    cout << *itor << endl;
}
1