473,549 Members | 2,723 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How I should write code then I can use operate "<<"

Hi all

I am confuse of how to override operate "<<"

Sample , I've got 2 class
class Terminal
{
public:
void printchar(strin g ch){
printf(ch); // don't care this
};
}
class Adapter
{
private:
void printWithPrefix (string str){
tm_ << prefix_ << str;
}

private:
string prefix_;
Terminal* tm_;

}
What I want to implement is

void foo(){
Terminal *term_ = new Terminal();

Adapter* adp_ = new Adapter(term_);

string str = "This is test string"
char ch = 'a'

adp_ << str << ch;

}
what's the right grammar?

If I have an other class A, when I want to using
class A;

adp_<< A;

what's that grammar?


thank you very much
key9


Sep 12 '06 #1
3 2151
Hey Key9,

Here's a small example showing how the << operator can be overloaded:

class Foo
{
public:
void printFoo() const {
std::cout << foo_ << std::endl;
}
/** Implement this smarter, but you get the idea */
Foo& operator <<(const std::string &foo){
foo_ = foo;
return *this;
}
private:
std::string foo_;
};

Example:
Foo foo;
foo << "hello foo";
foo.printFoo();

Also check out:
http://www.parashift.com/c++-faq-lit...erloading.html

// Morten
key9 wrote:
Hi all

I am confuse of how to override operate "<<"

Sample , I've got 2 class
class Terminal
{
public:
void printchar(strin g ch){
printf(ch); // don't care this
};
}
class Adapter
{
private:
void printWithPrefix (string str){
tm_ << prefix_ << str;
}

private:
string prefix_;
Terminal* tm_;

}
What I want to implement is

void foo(){
Terminal *term_ = new Terminal();

Adapter* adp_ = new Adapter(term_);

string str = "This is test string"
char ch = 'a'

adp_ << str << ch;

}
what's the right grammar?

If I have an other class A, when I want to using
class A;

adp_<< A;

what's that grammar?


thank you very much
key9

Sep 12 '06 #2
key9 wrote:
Hi all

I am confuse of how to override operate "<<"
Sample , I've got 2 class

class Terminal
{
public:
void printchar(strin g ch){
printf(ch); // don't care this
};
}

class Adapter
{
private:
void printWithPrefix (string str){
tm_ << prefix_ << str;
}
private:
string prefix_;
Terminal* tm_;
}

What I want to implement is

void foo(){
Terminal *term_ = new Terminal();
Adapter* adp_ = new Adapter(term_);
string str = "This is test string"
char ch = 'a'
adp_ << str << ch;
}

what's the right grammar?
The operator<< is usually implemented as global function (in contrast to
a method that belongs to a class). In your case you need to define some
overloadings of operator<< for different types (these are not called
overridings, as you did).

For example to output a std::string you have to define something like this:

#include <sstream>

class Terminal
{
public:
void printchar(std:: string ch){
printf(ch.c_str ()); // don't care this
};
};

class Adapter
{
public:
// I had to insert this (rather dumb) constructor.
Adapter (Terminal* p_Terminal)
: tm_ (p_Terminal),
prefix_ ("TestPrefix ")
{}

public:
// Adapters print method must be public, else we
// can't access its functionality.
void printWithPrefix (std::string str)
{
tm_->printchar (prefix_);
tm_->printchar (str);
}
private:
std::string prefix_;
Terminal* tm_;
};

// These are the overloadings of operator<< for Terminals. They
// are not really necessary for this example, but nice to have.
Terminal& operator<< (Terminal& p_Terminal, std::string p_String)
{
// Let the terminal print the string as it is.
std::stringstre am Temp;
Temp << p_String;
p_Terminal.prin tchar (Temp.str ());
return p_Terminal;
}

Terminal& operator<< (Terminal& p_Terminal, int p_Number)
{
// Convert the number to a string and let the terminal print the
// text representation of the number.
std::stringstre am Temp;
Temp << p_Number;
p_Terminal.prin tchar (Temp.str ());
return p_Terminal;
}

Adapter& operator<< (Adapter& p_Adapter, std::string p_String)
{
// Let the terminal print the string as it is.
std::stringstre am Temp;
Temp << p_String;
p_Adapter.print WithPrefix (Temp.str ());
return p_Adapter;
}

Adapter& operator<< (Adapter& p_Adapter, int p_Number)
{
// Convert the number to a string and let the terminal print the
// text representation of the number.
std::stringstre am Temp;
Temp << p_Number;
p_Adapter.print WithPrefix (Temp.str ());
return p_Adapter;
}

// Instead of the above two overloadings you can
// use the following template:

//template <class t_ParameterType >
//Adapter& operator<< (Adapter& p_Adapter, t_ParameterType p_Parameter)
//{
// // Convert the number to a string.
// std::stringstre am Temp;
// Temp << p_Parameter;
// p_Adapter.print WithPrefix (Temp.str ());
// return p_Adapter;
//}

void foo()
{
Terminal *term_ = new Terminal();
Adapter adp_ (term_);
std::string str ("This is test string");
char ch = 'a';
(*term_) << str << ch;
adp_ << str;
}

int main ()
{
foo ();
return 0;
}

Now this source should be compilable (you should always post only such
programs that can actually be compiled, I had to correct numerous errors
in your source!)

Regards,
Stuart
Sep 12 '06 #3
Now this source should be compilable (you should always post only such
programs that can actually be compiled, I had to correct numerous errors
in your source!)
sorry for that ,and thank you very much

I am a computer fan ,but I am not a coder, so every time when I try to
design something , the problem always exist on grammar . It's my suffering.

thanks GOD there's kindness guys like you.
Sep 12 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2787
by: Eric A. Forgy | last post by:
Hello, I am just learning Java and am trying to write a method that does something like //=========================================== public Static List find(double array,double val,String relationalOp) { List list = new ArrayList();
7
9011
by: Ensoul Chee | last post by:
I used #include <iostream.h> int m; cout << "Hexadecimal == 0x" << hex << m << endl; to print value of m in hexadecimal mode. But I got the compile error like this couttest.cpp:20 `hex' undeclared (first use this function)
1
6804
by: Christian Schmidbauer | last post by:
Hello! I prepare my XML document like this way: ------------------------------------------------------- PrintWriter writer; Document domDocument; Element domElement; // Root tag
6
6633
by: Rate Spring | last post by:
hi, in win2000 and VC6, I operate a txt file. When I write a line data into file and add "\r\n" at the end of line, I find: fstream << "\r\n" write 3 chars : 0D 0D 0A fstream << "\n" write 2 chars : 0D 0A why?
2
5753
by: bissatch | last post by:
Hi, I am trying to use JavaScript to write a table column on a web page. The code is as follows: <html> <head> <script> function displaycount() {
4
1740
by: wangzhihuii | last post by:
Hi all, I'm really confused, can cout<<""; contribute anything to the routine ?!! my programm won't work properly without this trivial sentence. Sincerely vivian
12
6075
by: Filipe Sousa | last post by:
Hi! Could someone explain to me why this operation is not what I was expecting? int main() { int x = 2; std::cout << x << " " << x++ << std::endl; return 0; }
3
2158
by: Steven.Xu | last post by:
hi everybody, i am useing some classes which in System.Xml to deal with xml document. what can i do if the document include "<" or ">"? Thanks.
4
2929
by: ek | last post by:
I thought that the syntax for c++ in either winXP or linux was the same. In Ubuntu linux it works fine if I write: #include <string> using namespace std; int main() {
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7809
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.