Reputation: 35
Can anyone help me with this? I'm new here. Any help is most welcomed!
9.3.cpp: In constructor ‘Address::Address(int,std::string.int.std::string,std::String,std::String)’: 9.3.cpp:29:51:error:’this’ cannot be used as function
9.3.cpp: In member function ‘int Address::compareTo(const Address&)’: 9.3.cpp:39:26:error:’std::string’has no member named ‘compareTo’
#include<iostream>
using namespace std;
class Address {
int houseNumber;
string street;
int apartmentNumber;
string city;
string state;
string zipCode; // e.g., "47405-1234"
Address(int houseNumber,
string street,
// no apartmentNumber
string city,
string state,
string zipCode) {
this->houseNumber = houseNumber;
this->street = street;
this->city = city;
this->state = state;
this->zipCode = zipCode;
}
Address(int houseNumber,
string street,
int apartmentNumber,
string city,
string state,
string zipCode) {
this(houseNumber, street, city, state, zipCode);
this->apartmentNumber = apartmentNumber;
}
void print(void) {
std::cout << "Street: " << street << "\nCity: "
<< city << "\nState: " << state << "\nPostal Code: " << zipCode;
}
int compareTo(const Address &a) {
// same conventions as for Strings
return this->zipCode.compareTo(angel);
}
};
Upvotes: 1
Views: 194
Reputation: 153830
You code doesn't seem to be C++, rather Java or C#: C++ uses member initializer lists to delegate constructors to [sub-] objects (and delegating to another constructor of the same class is new in C++. Using a member-initializer list looks something like this:
class foo
{
std::string d_val;
public:
foo(std::string const& val)
: d_val(val)
{
}
foo()
: foo("default") // C++ 2011 only
{
}
};
Upvotes: 0
Reputation: 21351
You cannot use the this
pointer in this way
this(houseNumber, street, city, state, zipCode);
as it is not a function. It appears that you are trying to call the other constructor of your class inside the other constructor. This will not work as you intend - you cannot call a constructor like a member function - member functions are called on an instance of an objects whereas a constructor is used to create an object. You should just set the variables in the same way as you do in your other constructor, or even better do so using an initialiser list.
The other error should be resolved if you #include<string>
at the top of the header.
Upvotes: 0
Reputation: 409176
This line:
this(houseNumber, street, city, state, zipCode);
You can't call your own constructor, at least not like this. New in the C++11 standard is a way to do it using the initializer list:
Address(int houseNumber,
string street,
int apartmentNumber,
string city,
string state,
string zipCode)
: Address(houseNumber, street, city, state, zipCode)
{
this->apartmentNumber = apartmentNumber;
}
If your compiler does not support it yet, then you have to copy the code from the first constructor, or to put common initialization in a separate function to be called from both constructors.
Upvotes: 1