这是我之前的问题的后续跟进。我有一些应该运行正常的代码,并且它在大多数情况下都可以。当我运行它时,大多数main
方法都会运行,但是当执行getter方法时我会遇到分段错误。这是代码:
#include <iostream>
#include <string>
using namespace std;
class Person
{
protected:
string m_FirstName, m_LastName, m_email;
public:
Person(){}
Person(const string& firstName, const string& lastName) :
m_FirstName(firstName), m_LastName(lastName)
{}
string get_name() const
{
return m_FirstName;
}
string get_surname() const
{
return m_LastName;
}
bool has_email_p()
{
}
};
class Person_with_telephone: public Person
{
protected:
string m_telephone;
public:
Person_with_telephone(){}
Person_with_telephone(const string& telephone) : m_telephone(telephone)
{}
bool has_telephone_p()
{
if (m_telephone == "")
{
cout << "You have no phone number registered" << endl;
return false;
}
else
{
cout << "Your number is: " << m_telephone << endl;
return true;
}
}
string get_telephone() const
{
return m_telephone;
}
string set_telephone()
{
}
string get_telephone()
{
}
};
int main()
{
string f, l, ph;
cout << "Enter fist name: ";
cin >> f;
cout << "Enter Last name: ";
cin >> l;
cout << "Enter telephone number: ";
cin >> ph;
Person p(f, l);
Person_with_telephone pwt(ph);
cout << "Your name is: " << p.get_name() << " " << p.get_surname() << endl;
cout << "Has telephone? " << endl << " Your number is: " << pwt.get_telephone() << endl;
return 0;
}
当我编译它时编译很好,当我运行时,我会被要求输入姓名,姓氏和电话的三个输入,但当我输入最后一个值时,我得到这个:Odd segfault
答案 0 :(得分:1)
您没有在Person_with_telephone::get_telephone()
中返回任何内容。这将导致段错误。
如果你compile with proper warnings turned on那么你至少应该
main.cpp:32:9: warning: control reaches end of non-void function [-Wreturn-type]
}
^
main.cpp:69:3: warning: control reaches end of non-void function [-Wreturn-type]
}
^
main.cpp:74:3: warning: control reaches end of non-void function [-Wreturn-type]
}
^
3 warnings generated.
这会让你知道你需要在这些函数中使用return语句。
答案 1 :(得分:0)
您的bool has_email_p()
,string get_telephone()
和string set_telephone()
功能不起作用,或者更重要的是return
任何内容。